package com.moyo.service;

import com.moyo.model.*;
import com.moyo.repository.*;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 权限业务逻辑
 */
@Service
public class SysPermissionService {
    private final SysPermissionRepository permissionRepository = new SysPermissionRepository();
    private final SysRoleRepository roleRepository = new SysRoleRepository();
    private final SysRolePermissionRepository rolePermissionRepository = new SysRolePermissionRepository();
    private final SysUserRoleRepository userRoleRepository = new SysUserRoleRepository();

    /**
     * 获取用户的所有权限编码
     */
    public List<String> getUserPermissionCodes(Long userId) {
        // 获取用户的所有角色
        List<Long> roleIds = userRoleRepository.findByUserId(userId)
                .stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());
        
        // 获取这些角色的所有权限
        List<Long> permissionIds = roleIds.stream()
                .flatMap(roleId -> rolePermissionRepository.findByRoleId(roleId).stream())
                .map(SysRolePermission::getPermissionId)
                .distinct()
                .collect(Collectors.toList());
        
        // 获取权限编码
        return permissionIds.stream()
                .map(permissionRepository::findById)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .map(SysPermission::getCode)
                .collect(Collectors.toList());
    }

    /**
     * 获取用户的所有角色
     */
    public List<SysRole> getUserRoles(Long userId) {
        return userRoleRepository.findByUserId(userId)
                .stream()
                .map(SysUserRole::getRoleId)
                .map(roleRepository::findById)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
    }

    /**
     * 获取用户的所有权限
     */
    public List<SysPermission> getUserPermissions(Long userId) {
        List<Long> roleIds = userRoleRepository.findByUserId(userId)
                .stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());
        
        List<Long> permissionIds = roleIds.stream()
                .flatMap(roleId -> rolePermissionRepository.findByRoleId(roleId).stream())
                .map(SysRolePermission::getPermissionId)
                .distinct()
                .collect(Collectors.toList());
        
        return permissionIds.stream()
                .map(permissionRepository::findById)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
    }

    /**
     * 为角色分配权限
     */
    public void assignPermissionsToRole(Long roleId, List<Long> permissionIds, Long operatorId) {
        // 先删除原有权限
        rolePermissionRepository.deleteByRoleId(roleId);
        
        // 添加新权限
        LocalDateTime now = LocalDateTime.now();
        permissionIds.forEach(permissionId -> {
            SysRolePermission rolePermission = new SysRolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermission.setCreatedBy(operatorId);
            rolePermission.setUpdatedBy(operatorId);
            rolePermission.setCreateTime(now);
            rolePermission.setUpdateTime(now);
            rolePermissionRepository.save(rolePermission);
        });
    }

    /**
     * 为用户分配角色
     */
    public void assignRolesToUser(Long userId, List<Long> roleIds, Long operatorId) {
        // 先删除原有角色
        userRoleRepository.deleteByUserId(userId);
        
        // 添加新角色
        LocalDateTime now = LocalDateTime.now();
        roleIds.forEach(roleId -> {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRole.setCreatedBy(operatorId);
            userRole.setUpdatedBy(operatorId);
            userRole.setCreateTime(now);
            userRole.setUpdateTime(now);
            userRoleRepository.save(userRole);
        });
    }
} 